<script setup lang="ts">
import HomeHeader from '@/pages/home/component/HomeHeader.vue';
import to from '@/utils/to';
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import Location from '@/utils/location';
import HomeButtonList from '@/pages/home/component/HomeButtonList.vue';
import TabComponent from '@/pages/home/component/TabComponent.vue';
import { APP_ID } from '@/config/app';
import useLoading from '@/hooks/useLoading';
import HomeTemplate from '@/pages/home/component/HomeTemplate.vue';
import zPaging from 'z-paging/components/z-paging/z-paging.vue';
import CompPriceDiffPopup from '@/pages/home/component/CompPriceDiffPopup.vue';
import MergerCaseModal from '@/pages/home/component/MergerCaseModal.vue';
import RecordingModal from '@/components/RecordingModal.vue';
import DeviceListPopup from './component/DeviceListPopup.vue';

interface IState {
  beeperId: number;
  bgColor: string;
  beeperList: IGetCallListRes[];
  serverList?: IServerBtnListRes;
  defaultOpen: number;
  btnModelRelations: BtnModelRelations[];
  btnList: IServerBtnListBtnList[];
}
const { showLoading } = useLoading();
const store = useAppStore();
const { beeperParams, token, beeperId, headerHeight, tabbarHeight } = store.$state;
const initalState = () => {
  return { beeperId: beeperId || 0, bgColor: '', beeperList: [], serverList: undefined, defaultOpen: 1, btnModelRelations: [], btnList: [] };
};
const state = reactive<IState>(initalState());
const pagingRef = ref<InstanceType<typeof zPaging> | null>(null);

onLoad(async () => {
  if (token) {
    await fetchCallerList();
  } else {
    await fetchServerTemplate();
  }
});

watch(
  () => store.$state.beeperId,
  (value) => {
    state.beeperId = value;
  },
);

watch(
  () => store.$state.token,
  () => {
    Object.assign(state, initalState());
    fetchServerTemplate();
  },
);

// 请求呼叫器列表
const fetchCallerList = async () => {
  const [err, callList] = await to(HomeRequest.GetCallerList({ type: 2, hasLoading: true }));
  if (err) return;
  state.beeperList = callList.data;
  if (state.beeperList.length === 0) {
    state.beeperId = -1;
  } else if (state.beeperList.length > 0 && !state.beeperList.some((item) => item.id === beeperId)) {
    state.beeperId = callList.data[0].id;
  }
  await fetchServerTemplate();
};

// 请求服务模版
const fetchServerTemplate = async () => {
  let serverBtnListParams: any = { query: 0 };
  let address = {};
  if (beeperParams.latitude && beeperParams.longitude) {
    address = { latitude: beeperParams.latitude, longitude: beeperParams.longitude, provinceName: beeperParams.provinceName, cityName: beeperParams.cityName, areaName: beeperParams.areaName };
  } else {
    showLoading();
    const location = await Location.reverseGeocoderLocation();
    if (location) {
      address = { latitude: location.location.lat, longitude: location.location.lng, provinceName: location.address_component.province, cityName: location.address_component.city, areaName: location.address_component.district };
      store.$patch({
        beeperParams: { queryType: state.defaultOpen, ...address },
      });
    }
  }
  // 有呼叫器
  if (state.beeperId > 0) {
    const selectedBeeper = state.beeperList.find((item) => item.id === state.beeperId);
    serverBtnListParams = { query: 1, type: state.defaultOpen, beeperId: state.beeperId, beeperType: selectedBeeper?.beeperType, beeperVersion: selectedBeeper?.beeperVersion };
  } else if (state.beeperId === -1) {
    // 选中周边
    serverBtnListParams = { query: 1, ...address };
  } else {
    // 第一次进入小程序
    serverBtnListParams = { query: 0, ...address };
  }
  if (state.beeperId > 0 && store.$state.token) {
    const [err, serverList] = await to(HomeRequest.ServerBtnList({ ...serverBtnListParams, hasLoading: true }));
    if (err) return;
    state.serverList = serverList.data;
    state.beeperId = state.serverList.beeperId ? state.serverList.beeperId : -1;
    state.bgColor = state.serverList.bgColor ? state.serverList.bgColor : '';
    state.btnModelRelations = state.serverList.btnModelParam ? state.serverList.btnModelParam.btnModelRelations : [];
    state.btnList = serverList.data.btnList;
    state.defaultOpen = serverList.data.defaultOpen;
    store.$patch({ beeperId: state.beeperId });
  } else {
    const [err, serverList] = await to(HomeRequest.GetSurroundingTemplateData({ ...serverBtnListParams, appId: APP_ID, hasLoading: true }));
    if (err) return;
    state.serverList = undefined;
    state.beeperId = -1;
    state.defaultOpen = 2;
    store.$patch({ beeperId: -1 });
    state.btnList = serverList.data;
  }
  pagingRef.value?.complete();
};

// 呼叫器点击
const handleHeaderBeeperClick = async (payload: { id: number }) => {
  state.beeperId = payload.id;
  if (payload.id === -1) {
    state.defaultOpen = 2;
  } else {
    state.defaultOpen = state.beeperList.find((item) => item.id === payload.id)?.defaultOpen || 1;
  }
  store.removeShoppingCart(undefined);
  await fetchServerTemplate();
};
</script>

<template>
  <view class="w-screen">
    <HomeHeader :beeper-id="state.beeperId" :beeper-list="state.beeperList" :bg-color="state.bgColor" @selected="handleHeaderBeeperClick" />
    <view :style="{ height: `calc(100vh - ${headerHeight + tabbarHeight}px)` }">
      <z-paging ref="pagingRef" :auto-height="false" :fixed="false" :refresher-only="true" @onRefresh="fetchServerTemplate" refresher-theme-style="white">
        <template>
          <view class="px-[12px] pt-[12px] pos-relative" v-if="state.defaultOpen === 1 && state.serverList?.btnStyle === 1 && state.btnModelRelations.length > 0 && state.btnModelRelations[0].moduleType === 5">
            <view class="top-img-bg c-bg" :style="{ backgroundColor: state.bgColor }" />
            <view class="c-br overflow-hidden h-[140px]">
              <van-image width="100%" height="100%" fit="cover" :src="state.btnModelRelations[0].bigImgUrl" />
            </view>
          </view>
          <TabComponent v-if="state.serverList && state.serverList?.showLevel === 0" :default-open="state.defaultOpen" @change="({ defaultOpen }) => (state.defaultOpen = defaultOpen)" />
          <HomeTemplate v-if="state.defaultOpen === 1 && state.serverList?.btnStyle === 1" :server-list="state.serverList" :btn-model-relations="state.btnModelRelations" />
          <HomeButtonList v-if="state.defaultOpen === 2 || state.serverList?.btnStyle !== 1" :btn-list="state.btnList" />
        </template>
      </z-paging>
    </view>
  </view>

  <!-- 设备列表弹窗 -->
  <DeviceListPopup />
  <!-- 补差价弹窗组件 -->
  <CompPriceDiffPopup />
  <!-- 组合按钮弹窗组件 -->
  <MergerCaseModal />
  <!-- 录音组件 -->
  <RecordingModal />
  <TabBar active-tab="首页" />
</template>
<style lang="scss" scoped>
.top-img-bg {
  position: absolute;
  bottom: 0;
  left: -20%;
  z-index: -1;
  width: 140%;
  height: 190%;
  content: '';
  transform: translateY(-10%);
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
}

:deep(.van-notice-bar) {
  padding: 0 !important;
}
</style>
